package com.lzx.adx.report.controller.v1.qimao;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.redis.RedisUtils;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzs.adx.commmon.constant.RedisCacheKey;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.common.CommonReportRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.DynamicRequestLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping("/qi/mao")
@RestController
@Slf4j
public class QiMaoController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    public static final   String apiDesc="七猫";

    @Autowired
    private DynamicRequestLimiter dynamicRequestLimiter;


    @Autowired
    private RedisUtils redisUtils;


    @GetMapping("/report")
    public ResponseEntity report(CommonReportRequest commonReportRequest, HttpServletRequest request){
        log.info("接收到七猫【{}】的请求参数为{}",apiDesc, JsonUtils.toJsonString(commonReportRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO=reportMapper.toReportDTO(commonReportRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(commonReportRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis()/1000));
        reportExecutor.execute(()->{
            reportService.save(reportDTO);
        });

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(commonReportRequest.getDspId());
        JSONObject jsonObject = JSONObject.parseObject(accountDTO.getSspExtend());

        ResponseEntity<Result> ok =dynamicRequestLimiter.getResultResponseEntity(jsonObject, reportDTO);
        if (ok != null) return ok;

        //通过的
        redisUtils.addToList(RedisCacheKey.qimao_callback_key, reportDTO.getBizRequestId());

        return ResponseEntity.ok(new Result());
    }




    @GetMapping("/callback")
    public ResponseEntity<?> callback(String requestId, String event_type) {
        log.info("接收了七猫回调信息，请求流水号{},回调类型为{}", requestId, event_type);
        log.info("reportService---"+reportService);
        //1.把转换结果更新到数据库
        Map<String,Object> params=new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if(CollectionUtil.isNotEmpty(list)){
            reportDTO = list.get(0);
            reportDTO.setResultType(event_type);
            reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
            reportDTO.setUpdateTime(new Date());
            reportService.update(reportDTO);
        }else{
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        String callback = reportDTO.getCallback()+"&event_type=3003&timestamp="+ System.currentTimeMillis();

        log.info("七猫请求参数为{}",callback);
        String result = HttpUtil.get(callback);
        log.info("七猫响应结果为{}",result);

        return ResponseEntity.ok(new Result());
    }



}
